import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Dept } from './dept.model';
import { DeptCreateData } from './dept.dto'
import { RESPONSE_CODE } from "@/enums/code";

const transformTree = (depts: any[]): any[] => {
  const map: { [key: string]: any } = {};
  const roots: any[] = [];
  const items = depts;

  items.forEach((item) => {
    const {
      id,
      name,
      isLock,
      parentId,
      deptCode,
      deptLevel,
      weight,
      createTime,
    } = item.dataValues;
    map[id] = {
      id,
      name,
      isLock,
      parentId,
      deptCode,
      deptLevel,
      weight,
      createTime,
      children: [],
    };
  });
  items.forEach((item) => {
    const { id, parentId } = item.dataValues;
    if (map[parentId]) {
      map[parentId].children.push(map[id]);
    } else {
      roots.push(map[id]);
    }
  });
  return roots;
};


@Injectable()
export class DeptService {

  constructor(
    @InjectModel(Dept)
    private deptModel: typeof Dept,
  ) { }

  async getDeptTree() {
    const depts = await this.deptModel.findAll({
      attributes: [
        "id",
        "name",
        "isLock",
        "parentId",
        "deptCode",
        "deptLevel",
        "weight",
        "createTime",
        "updateTime"
      ]
    });
    const tree = transformTree(depts)
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: tree,
      msg: null
    }
  }

  async addDept(data: DeptCreateData) {
    await this.deptModel.create({
      ...data,
      isLock: data.enable
    })

    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null
    }
  }

  /**
   * 通用方法
   * @param methods 方法
   * @param query query 条件
   * @returns 
   */
  async publicMethods(methods: string, query: any) {
    return await this.deptModel[methods]({ ...query });
  }
}
